package LC;

import java.util.HashMap;

public class Lc904 {
    public static void main(String[] args) {
        System.out.println(new Lc904().totalFruit(new int[]{1, 2, 1}));
    }
    public int totalFruit(int[] tree) {
        int left=0,right =0;
        int num =0 ,ans =0;
        HashMap<Integer, Integer> map = new HashMap<>();
        while (true){
            num++;
            if(right==tree.length) break;
            if(map.containsKey(tree[right])){
                map.put(tree[right],map.get(tree[right])+1);
            }else{
                map.put(tree[right],1);
            }
            if(map.size()==2){
                ans = Math.max(ans,num);
            }
            while (map.size()>2){
                Integer l = map.get(tree[left]);
                l--;
                if(l==0){
                    map.remove(tree[left]);
                    break;
                }else{
                    map.put(tree[left],l);
                }
                left ++ ;
                num--;
            }
            right++;
        }
        return ans;
    }
}
